package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.data.hdfs.HdfsManager;
import team.bluepen.supermarket.util.StringUtil;
import team.bluepen.supermarket.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件删除
 * @author Kai
 */
@WebServlet(name = "FileDeleteServlet", urlPatterns = "/api/file-delete")
public class FileDeleteServlet extends BaseServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");
        String path = req.getParameter("path");
        if (StringUtil.isEmpty(type)) {
            resp.sendRedirect("/file.jsp");
            return;
        }

        if ("all".equalsIgnoreCase(type)) {
            HdfsManager.getInstance().delete(Constant.TEMP_DIRECTORY);
            Error state = HdfsManager.getInstance().delete(Constant.UPLOAD_DIRECTORY);
            if (!state.getState()) {
                sendRedirect(resp, state);
                return;
            }
        } else if ("file".equalsIgnoreCase(type)) {
            if (StringUtil.isEmpty(path)) {
                sendRedirect(resp, Error.ERROR_NULL);
                return;
            }
            Error state = HdfsManager.getInstance().delete(path);
            if (!state.getState()) {
                sendRedirect(resp, state);
                return;
            }
        } else if ("output".equalsIgnoreCase(type)) {
            Error state = HdfsManager.getInstance().delete(Constant.OUTPUT_DIRECTORY);
            if (!state.getState()) {
                sendRedirect(resp, state);
                return;
            }
        }

        resp.sendRedirect("/file.jsp");
    }

    private static void sendRedirect(HttpServletResponse resp, Error error) throws IOException {
        resp.sendRedirect("/file.jsp?error=" + error.getValue());
    }
}
